<template>
  <div class="content-view">

    <!-- 加载和错误状态 -->
    <div v-if="loading" class="loading">加载中...</div>
    <div v-if="error" class="error">{{ error }}</div>

    <!-- 帖子内容及互动区域 -->
    <div v-if="content && !loading && !error" class="post">
      <h1 class="title">{{ content.title }}</h1>
      <div class="content-body" v-html="content.content"></div>
      <div class="back-button">
        <button @click="goBack">← 返回</button>
      </div>
      <!-- 互动数据和操作按钮 -->
      <div class="interaction-bar">
        <div class="stats">
          <span class="like-count">点赞: {{ content.likeCount || 0 }}</span>
          <span class="favorite-count">收藏: {{ content.favoriteCount || 0 }}</span>
        </div>
        <div class="actions">
          <button
              class="like-btn"
              :class="{ liked: isLiked }"
              @click="handleLike"
          >
            {{ isLiked ? '取消点赞' : '点赞' }}
          </button>
          <button
              class="favorite-btn"
              :class="{ favorited: isFavorited }"
              @click="handleFavorite"
          >
            {{ isFavorited ? '取消收藏' : '收藏' }}
          </button>
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comment-section">
        <h3>评论区</h3>

        <!-- 评论输入框 -->
        <div class="comment-input">
          <textarea
              v-model="newComment"
              placeholder="写下你的评论..."
              rows="3"
          ></textarea>
          <button @click="submitComment">发布评论</button>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <div v-for="comment in comments" :key="comment.commentId" class="comment-item">
            <div class="comment-header">
              <span class="commenter">用户{{ comment.commenterId }}</span>
              <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-actions">
              <button
                  class="comment-like"
                  :class="{ liked: comment.isLiked }"
                  @click="likeComment(comment.commentId)"
              >
                {{ comment.likeCount || 0 }} 点赞
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ContentView',
  data() {
    return {
      content: null,
      comments: [],
      loading: true,
      error: '',
      newComment: '',
      isLiked: false,
      isFavorited: false,
      currentUserId: 2,
      currentCtid: null,
      likeCount: 0,
      favoriteCount: 0,   // 明确初始化
      commentCount: 0
    };
  },
  created() {
    console.log('开始加载页面！！！');
    // 从路由参数获取ctid，没有则使用默认值80
    const ctid = this.$route.query.ctid ? parseInt(this.$route.query.ctid) : 259;
    console.log(ctid);
    this.currentCtid = ctid;
    this.loadContent(ctid);
    this.checkInteractionStatus();
    this.loadComments(ctid);
  },
  methods: {
    // 加载帖子内容
    async loadContent(ctid) {
      try {
        this.loading = true;
        const res = await this.$axios.get(`/api/create/content/detail?ctid=${ctid}`);
        if (res.data.code === 200) {
          this.content = res.data.data;
        } else {
          this.error = '加载帖子失败: ' + (res.data.message || '未知错误');
        }
      } catch (err) {
        this.error = '加载帖子失败: ' + (err.response?.data?.message || err.message);
      } finally {
        this.loading = false;
      }
    },
    goBack() {
      this.$router.back(); // 返回上一页
    },

    // 加载评论列表
    async loadComments(ctid) {
      try {
        const res = await this.$axios.get(`/create/comments?ctid=${ctid}`);
        if (res.data.code === 200) {
          this.comments = res.data.data;
        } else {
          console.error('加载评论失败:', res.data.message);
        }
      } catch (err) {
        console.error('加载评论请求失败:', err);
      }
    },

    // 检查用户互动状态（点赞/收藏）
    async checkInteractionStatus() {
      try {
        // 检查点赞状态
        const likeRes = await this.$axios.get(`/create/checkLike?uid=${this.currentUserId}&ctid=${this.currentCtid}`);
        if (likeRes.data.code === 200) {
          this.isLiked = likeRes.data.data;
        }

        // 检查收藏状态
        const favoriteRes = await this.$axios.get(`/favorite/check?uid=${this.currentUserId}&ctid=${this.currentCtid}`);
        if (favoriteRes.data.code === 200) {
          this.isFavorited = favoriteRes.data.data;
        }
      } catch (err) {
        console.error('检查互动状态失败:', err);
      }
    },

    // 处理点赞/取消点赞
    async handleLike() {
      try {
        if (this.isLiked) {
          await this.$axios.post(`/create/unlike`, null, {
            params: {likerId: this.currentUserId, ctid: this.currentCtid}
          });
          this.content.likeCount--;
        } else {
          await this.$axios.post(`/create/like`, null, {
            params: {likerId: this.currentUserId, ctid: this.currentCtid}
          });
          this.content.likeCount++;
        }
        this.isLiked = !this.isLiked;
      } catch (err) {
        alert('操作失败: ' + (err.response?.data?.message || err.message));
      }
    },

    // 处理收藏/取消收藏
    async handleFavorite() {
      try {
        if (this.isFavorited) {
          await this.$axios.post(`/favorite/remove`, null, {
            params: { uid: this.currentUserId, ctid: this.currentCtid }
          });
          this.content.favoriteCount--;
        } else {
          await this.$axios.post(`/favorite/add`, null, {
            params: { uid: this.currentUserId, ctid: this.currentCtid }
          });
          this.content.favoriteCount++;
        }
        this.isFavorited = !this.isFavorited; // 只在成功后更新状态
      } catch (err) {
        alert('操作失败: ' + (err.response?.data?.message || err.message));
      }
    },

    // 发布评论
    async submitComment() {
      if (!this.newComment.trim()) return;

      try {
        await this.$axios.post(`/create/comment`, null, {
          params: {
            commenterId: this.currentUserId,
            ctid: this.currentCtid,
            content: this.newComment
          }
        });

        // 刷新评论列表并清空输入框
        this.loadComments(this.currentCtid);
        this.newComment = '';
        this.content.commentCount++;
      } catch (err) {
        alert('评论失败: ' + (err.response?.data?.message || err.message));
      }
    },

    // 评论点赞
    async likeComment(commentId) {
      try {
        const comment = this.comments.find(c => c.commentId === commentId);
        if (comment.isLiked) {
          await this.$axios.post(`/create/comment/unlike`, null, {
            params: {likerId: this.currentUserId, commentId}
          });
          comment.likeCount--;
        } else {
          await this.$axios.post(`/create/comment/like`, null, {
            params: {likerId: this.currentUserId, commentId}
          });
          comment.likeCount++;
        }
        comment.isLiked = !comment.isLiked;
      } catch (err) {
        alert('评论点赞失败: ' + (err.response?.data?.message || err.message));
      }
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      return new Date(dateStr).toLocaleString();
    }
  }
};
</script>

<style scoped>
.content-view {
  padding-top: 10rem; /* 适配固定 header */
  max-width: 800px;
  margin: 20px auto;

  background-color: #f9f9f9;
  border-radius: 8px;
}

.loading, .error {
  text-align: center;
  padding: 20px;
  font-size: 16px;
}

.error {
  color: #dc3545;
}

.post {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 24px;
  margin: 0 0 20px 0;
  color: #333;
}

.content-body {
  font-size: 16px;
  line-height: 1.8;
  margin: 0 0 30px 0;
  color: #333;
}

/* 互动栏样式 */
.interaction-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  margin-bottom: 30px;
}

.stats {
  display: flex;
  gap: 20px;
  color: #666;
}

.actions {
  display: flex;
  gap: 10px;
}

button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.like-btn {
  background-color: #e6f7ff;
  color: #1890ff;
}

.like-btn.liked {
  background-color: #1890ff;
  color: white;
}

.favorite-btn {
  background-color: #fff0f0;
  color: #f5222d;
}

.favorite-btn.favorited {
  background-color: #f5222d;
  color: white;
}

/* 评论区样式 */
.comment-section {
  margin-top: 30px;
}

.comment-input {
  margin-bottom: 20px;
}

.comment-input textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  margin-bottom: 10px;
}

.comment-input button {
  background-color: #1890ff;
  color: white;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  color: #666;
  font-size: 14px;
}

.comment-content {
  margin-bottom: 8px;
  line-height: 1.6;
}

.comment-actions {
  font-size: 14px;
}

.comment-like {
  background: none;
  border: none;
  color: #666;
  padding: 2px 5px;
  cursor: pointer;
}

.comment-like.liked {
  color: #1890ff;
}

.back-button {
  margin-bottom: 10px;
}

.back-button button {
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ccc;
  padding: 6px 12px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
}

.back-button button:hover {
  background-color: #e0e0e0;
}


</style>